/**
 * Copyright (c) 2018, 西安星沙网络科技-版权所有
 *
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/lgpl-3.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.waleychain.exchange.consumer.shiro;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import cn.waleychain.exchange.core.Global;
import cn.waleychain.exchange.core.constant.DDIC;
import cn.waleychain.exchange.core.entity.TokenEntity;
import cn.waleychain.exchange.core.utils.StringUtils;
import cn.waleychain.exchange.feign.UserServiceFeign;
import cn.waleychain.exchange.model.UserInfo;

/**
 * 认证
 * @author chenx
 * @date 2018年3月27日 下午3:27:34
 * @version 1.0 
 */
public class UserShiroRealm extends AuthorizingRealm {

	@Autowired
	private UserServiceFeign userFign;
	
	/**
	 * 认证，验证是调用
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        TokenEntity token = (TokenEntity) principals.getPrimaryPrincipal();
        try {
        	
            List<String> roles = token.getRoleList();
            if (roles != null && roles.size() > 0) {
            	for (String role : roles) {
                    authorizationInfo.addRole(role);
                }
            }
            
            List<String> permissions = token.getResourceList();
            if (permissions != null && roles.size() > 0) {
                 for (String perm : permissions) {
                     authorizationInfo.addStringPermission(perm);
                 }
            }
           
        } catch (Exception e) {
        	// 不做处理
            e.printStackTrace();
        }
        
        return authorizationInfo;
	}

	/**
	 * 认证，登录是调用
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {

		try {
			
			String username = null;
			String password = null;
			String subSystemCode = null;
			LoginAuthToken authToken = null;
			if (auth instanceof LoginAuthToken) {
				authToken = (LoginAuthToken) auth;
				username = authToken.getUsername();
				password = new String((char[]) auth.getCredentials());
				subSystemCode = authToken.getSubSystemCode();
			} else {
				username = (String) auth.getPrincipal();
				String[] arr = StringUtils.split(username, Global.DEFAULT_SEPARATOR);
				password = new String((char[]) auth.getCredentials());
				username = arr[0];
				subSystemCode = arr[1];
			}
			
			UserInfo userInfo = userFign.login(username, password);
			
			if (userInfo == null) {
				throw new UnknownAccountException();
			}
			
			if (DDIC.UserAccountStatus.DISABLED.id == userInfo.getStatus()) { //账户冻结
			    throw new LockedAccountException();
			}
			
			TokenEntity token = new TokenEntity();
			token.setUnionId(userInfo.getUserId());
			token.setSubSystemCode(subSystemCode);
			
			if (true) {
        		// 超级管理员
				List<String> roleList = new ArrayList<>();
				roleList.add(Global.SUPER_ADMIN_DEFAULT_ROLE);
				token.setRoleList(roleList);
				
				List<String> permissionList = new ArrayList<>();
				permissionList.add(Global.SUPER_ADMIN_DEFAULT_PERMISSION);
        		token.setResourceList(permissionList);
				
        	}
			
			SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
					token, 
			        password, //密码
			        ByteSource.Util.bytes(username),//salt=username+salt
			        getName()  //realm name
			);
			
			return authenticationInfo;
		} catch (Exception e) {
			e.printStackTrace();
			throw new AuthenticationException();
		}
		
	}

}
